import time
from datetime import datetime, timedelta
from flask import current_app, jsonify
from flask import g
from flask import redirect
from flask import render_template
from flask import request
from flask import session
from flask import url_for

from info import constants, db
from info.models import User, News
from info.modules.admin import admin_blu
from info.utils.common import user_login_data
from info.utils.response_code import RET

"""执行审核"""
@admin_blu.route('/news_review_action', methods=["POST"])
def news_review_action():
    """新闻审核"""

    # 执行审核操作

    # 1.获取参数
    news_id = request.json.get("news_id")
    action = request.json.get("action")

    # 2.判断参数
    if not all([news_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    if action not in ("accept", "reject"):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    news = None
    try:
        # 3.查询新闻
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)

    if not news:
        return jsonify(errno=RET.NODATA, errmsg="未查询到数据")

    # 4.根据不同的状态设置不同的值
    if action == "accept":
        news.status = 0
    else:
        # 拒绝通过，需要获取原因
        reason = request.json.get("reason")
        if not reason:
            return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
        news.reason = reason
        news.status = -1

    # 保存数据库
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="数据保存失败")
    return jsonify(errno=RET.OK, errmsg="操作成功")




"""新闻审核"""
@admin_blu.route('/news_review_detail/<int:news_id>')

def news_review_detail(news_id):
    """新闻审核"""
    # 通过id查询新闻
    news = None
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)

    if not news:
        return render_template('admin/news_review_detail.html', data={"errmsg": "未查询到此新闻"})

    # 返回数据
    data = {"news": news.to_dict()}
    return render_template('admin/news_review_detail.html', data=data)





"""新闻审核列表"""
@admin_blu.route('/news_review')
def news_review():
    """返回待审核新闻列表"""

    page = request.args.get("p", 1)
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    news_list = []
    current_page = 1
    total_page = 1

    try:
        paginate = News.query.filter(News.status != 0) \
            .order_by(News.create_time.desc()) \
            .paginate(page, constants.ADMIN_NEWS_PAGE_MAX_COUNT, False)

        news_list = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    news_dict_list = []
    for news in news_list:
        news_dict_list.append(news.to_review_dict())

    context = {"total_page": total_page, "current_page": current_page, "news_list": news_dict_list}

    return render_template('admin/news_review.html', data=context)





"""用户列表"""
@admin_blu.route('/user_list')
def user_list():
    """获取用户列表"""

    # 获取参数
    page = request.args.get("p", 1)
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    # 设置变量默认值
    users = []
    current_page = 1
    total_page = 1

    # 查询数据
    try:
        paginate = User.query.filter(User.is_admin == False).order_by(User.last_login.desc()).paginate(page, constants.ADMIN_USER_PAGE_MAX_COUNT, False)
        users = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    # 将模型列表转成字典列表
    users_list = []
    for user in users:
        users_list.append(user.to_admin_dict())

    context = {"total_page": total_page, "current_page": current_page, "users": users_list}
    return render_template('admin/user_list.html',
                           data=context)






"""用户统计表"""
@admin_blu.route('/user_count',methods=["GET","POST"])
def user_count():
    #查询总人数
    total_count=0
    try:
        total_count = User.query.filter(User.is_admin == False).count()
    except Exception as e:
        current_app.logger.error(e)


    #查询月新增数
    mon_count=0
    try:
        # 当前时间
        now = time.localtime()
        #当前年和月,指定第一天
        mon_begin = '%d-%02d-01' % (now.tm_year, now.tm_mon)
        #将时间字符串转换成时间对象用strptime
        mon_begin_date = datetime.strptime(mon_begin, '%Y-%m-%d')
        #当前本月创建用户的时间大于本月最开始的时间就能知道本月创建的人数
        mon_count = User.query.filter(User.is_admin == False, User.create_time >= mon_begin_date).count()
    except Exception as e:
        current_app.logger.error(e)

    #日增人数
    day_count=0
    try:
        #当年当月当天的凌晨0点
        day_begin = '%d-%02d-%02d' % (now.tm_year, now.tm_mon, now.tm_mday)
        day_begin_date = datetime.strptime(day_begin, '%Y-%m-%d')
        # 每日的人赠数
        day_count = User.query.filter(User.is_admin == False, User.create_time > day_begin_date).count()
    except Exception as e:
        current_app.logger.error(e)


    # 查询图表信息
    # 获取到当天00:00:00时间
    day_begin_today = '%d-%02d-%02d' % (now.tm_year, now.tm_mon, now.tm_mday)
    now_date= datetime.strptime(day_begin_today, '%Y-%m-%d')

    # 定义空数组，保存数据
    #  1 时间
    active_date = []
    # 2 访问次数
    active_count = []

    # 依次添加数据，再反转
    for i in range(0, 31):
        day_begin = now_date - timedelta(days=i)
        day_end = now_date - timedelta(days=(i - 1))
        active_date.append(day_begin.strftime('%Y-%m-%d'))
        count = 0
        try:
            count = User.query.filter(User.is_admin == False, User.last_login >= day_begin,
                                      User.last_login < day_end).count()
        except Exception as e:
            current_app.logger.error(e)
        active_count.append(count)

    active_date.reverse()
    active_count.reverse()

    data = {"total_count": total_count,
            "mon_count": mon_count,
            "day_count": day_count,
            "active_date": active_date,
            "active_count": active_count}

    return render_template("admin/user_count.html", data=data)




"""跳转首页"""
@admin_blu.route('/index')
@user_login_data
def index():
    user = g.user
    return render_template('admin/index.html', user=user.to_dict())




"""登陆页面"""
@admin_blu.route('/login',methods=["GET","POST"])
def login():
    if request.method=="GET":
        #判断当前是否有登陆,如果有登陆直接重定向到管理员后台主页
        user_id=session.get("user_id",None)
        is_admin=session.get("is_admin",False)
        if user_id and is_admin:
            return redirect(url_for('admin.index'))

        return render_template("admin/login.html")

    #取到登陆的参数
    username=request.form.get("username")
    password=request.form.get("password")

    # 判断参数是否有值
    if not all([username,password]):
        return render_template("admin/login.html",errmsg="参数错误")

    #查询当前用户

    try:
        user = User.query.filter(User.mobile == username, User.is_admin == True).first()
    except Exception as e:
        current_app.logger.error(e)
        return render_template("admin/login.html", errmsg="用户查询错误")

    #判断用户是否存在
    if not user:
        return render_template("admin/login.html", errmsg="用户不存在")

    #校验密码
    if not user.check_passowrd(password):
        return render_template("admin/login.html", errmsg="密码错误")


    #校验是否是管理员
    if not user.is_admin:
        return render_template('admin/login.html', errmsg="用户权限错误")

    #保存登录信息
    session["user_id"] = user.id
    session["nick_name"] = user.nick_name
    session["mobile"] = user.mobile
    session["is_admin"] = True

    # 重定向到首页面
    return redirect(url_for('admin.index'))